package com.neulogistics.core.substation.api.application.command.handler;

import com.blackto.lib.mediat.unicast.IRequestHandler;
import com.neulogistics.core.substation.api.application.command.AssignCourierCommand;
import com.neulogistics.core.substation.domain.exception.SubstationDomainException;
import com.neulogistics.core.substation.domain.model.aggregate.TaskOrder;
import com.neulogistics.core.substation.domain.model.enumeration.TaskStatus;
import com.neulogistics.core.substation.domain.repository.ITaskOrderRepository;
import com.neulogistics.infrastructure.common.serviceresult.BaseResponse;
import com.neulogistics.infrastructure.common.serviceresult.ErrorCode;
import com.neulogistics.infrastructure.common.serviceresult.ResultUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AssignCourierCommandHandler implements IRequestHandler<AssignCourierCommand, BaseResponse<Boolean>> {
    @Resource
    ITaskOrderRepository taskOrderRepository;

    @Override
    public BaseResponse<Boolean> handle(AssignCourierCommand command) throws Exception {
        TaskOrder taskOrder = taskOrderRepository.findById(command.taskId);
        if(taskOrder.getTaskStatus() != TaskStatus.To_Be_Assigned){
            throw new SubstationDomainException(ErrorCode.OPERATION_ERROR, "错误的任务单状态");
        }

        taskOrder.setCourierInfo(command.courierInfo);
        taskOrder.setTaskStatus(TaskStatus.To_Be_Picked);
        taskOrderRepository.save(taskOrder);

        return ResultUtils.success(Boolean.TRUE);
    }
}
